package com.algorithm.ch2.lzr.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字谜分组
 * 给定一个字符串数组，将字母异位词组合在一起。字母异位词指字母相同，但排列不同的字符串。
 * <p>
 * 输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
 * 输出:
 * [
 * ["ate","eat","tea"],
 * ["nat","tan"],
 * ["bat"]
 * ]
 *
 * @author lzr
 * @date 2018/11/15
 */
public class GroupAnagrams {

    public static void main(String[] args) {
        String[] s = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> lists = groupAnagrams(s);
    }


    /**
     * 对字符排序分组
     *
     * @param strs
     * @return
     */
    public static List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) {
            return Collections.emptyList();
        }
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String s = String.valueOf(chars);
            if (map.get(s) == null) {
                List<String> sList = new ArrayList<>();
                sList.add(str);
                map.put(s, sList);
            } else {
                List<String> sList = map.get(s);
                sList.add(str);
            }
        }
        List<List<String>> rs = new ArrayList<>();
        for (String s : map.keySet()) {
            rs.add(map.get(s));
        }
        return rs;
    }

}
